package com.example.himalaya.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.widget.ImageView;

import com.example.himalaya.R;


/**
 * 帮助给图片加一个毛玻璃的效果
 */
public class ImageBlur {
    public static void makeBlur(ImageView imageView, Context context) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();

        Bitmap bitmap = drawable.getBitmap();

        // Second parametre is radius max : 25
        Bitmap blurred = blurRenderScript(bitmap, 23, context);

        // radius decide blur amount
        imageView.setImageBitmap(blurred);
    }


    private static Bitmap blurRenderScript(Bitmap SmallBitmap, int radius, Context context) {
        Bitmap smallBitmap = RGB565toRGB888(SmallBitmap);

        Bitmap bitmap = Bitmap.createBitmap(smallBitmap.getWidth(), smallBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        RenderScript renderScript = RenderScript.create(context);
        Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
        Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
        ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        blur.setInput(blurInput);
        blur.setRadius(radius);
        blur.forEach(blurOutput);
        blurOutput.copyTo(bitmap);
        renderScript.destroy();
        return bitmap;
    }

    private static Bitmap RGB565toRGB888(Bitmap img) {
        // 获取像素点的数量
        int numPixels = img.getWidth() * img.getHeight();

        int[] pixels = new int[numPixels];

        // Get JPEG pixels, Each int in the color value for one pixel.
        img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());

        // Create a Bitmap of the appropriate format.
        Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);

        // Set RGB pixels.
        result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());

        return result;
    }

    public static void setPictureMakeBlur(ImageView img, Context context) {
        img.setImageResource(R.mipmap.default_picture);

        Drawable drawable = img.getDrawable();

        if (drawable != null) {
            // 做一个毛玻璃的效果
            ImageBlur.makeBlur(img, context);
        }
    }
}
